﻿// owner 蒋家伟

#include "FieldReflectManager.h"

// jsdk
#include "Dbg_Warn_Define.h"

using namespace jsdk;

jsdk::FieldReflectManager::FieldReflectManager(const UniqueId& ownerClassTypeUid, const std::wstring& ownerClassTypeName) :
    m_ownerClassTypeName(ownerClassTypeName),
    m_ownerClassTypeUid(ownerClassTypeUid)
{
}

bool jsdk::FieldReflectManager::registerReflectField(OwnerPtr<IClassFieldDescriptor> opClassFieldDescriptor)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(opClassFieldDescriptor, L"传入空字段描述符", L"蒋家伟", L"2023-11-29");
    std::wstring variableName = opClassFieldDescriptor->getVariableName();
    bool success =  m_variableNameToFieldDescriptorList.emplace_back(variableName, transformOwnerShip(opClassFieldDescriptor));
    DBG_WARN_AND_RETURN_FALSE_UNLESS(success, this->getOwnerClassTypeName() + L"的" + variableName + L"字段反射注册失败", L"蒋家伟", L"2023-11-16");
    return success;
}

uint64_t jsdk::FieldReflectManager::getFieldCount() const
{
    return m_variableNameToFieldDescriptorList.size();
}

const jsdk::IClassFieldDescriptor* jsdk::FieldReflectManager::getFieldDescriptor(const std::wstring& fieldVariableName) const
{
    auto iter = m_variableNameToFieldDescriptorList.find(fieldVariableName);
    if (iter != m_variableNameToFieldDescriptorList.cend())
    {
        return iter->second.get();
    }
    else
    {
        // 加上前缀
        iter = m_variableNameToFieldDescriptorList.find(L"m_" + fieldVariableName);
        if (iter != m_variableNameToFieldDescriptorList.cend())
        {
            return iter->second.get();
        }
    }

    return nullptr;
}

const std::wstring& jsdk::FieldReflectManager::getOwnerClassTypeName() const
{
    return m_ownerClassTypeName;
}

const jsdk::UniqueId& jsdk::FieldReflectManager::getOwnerClassTypeUid() const
{
    return m_ownerClassTypeUid;
}

void jsdk::FieldReflectManager::setClassAddress(void* pClassAddress)
{
    for (auto& iter : m_variableNameToFieldDescriptorList)
    {
        DBG_WARN_AND_CONTINUE_UNLESS(iter.second, m_ownerClassTypeName + L" 存在空字段描述", L"蒋家伟", L"2023-11-30");
        iter.second->setClassAddress(pClassAddress);
        iter.second->setOwnerClassNameAndUid(getOwnerClassTypeName(), getOwnerClassTypeUid());
    }
}

jsdk::IClassFieldDescriptor* jsdk::FieldReflectManager::getFieldDescriptor(const std::wstring& fieldVariableName)
{
    auto iter = m_variableNameToFieldDescriptorList.find(fieldVariableName);
    if (iter != m_variableNameToFieldDescriptorList.end())
    {
        return iter->second.get();
    }
    else
    {
        // 加上前缀
        iter = m_variableNameToFieldDescriptorList.find(L"m_" + fieldVariableName);
        if (iter != m_variableNameToFieldDescriptorList.end())
        {
            return iter->second.get();
        }
    }
    // 加上前缀
    return nullptr;
}
